//
//  YBPlayVC.m
//  WuyouTang
//
//  Created by YB007 on 2019/11/29.
//  Copyright © 2019 cat. All rights reserved.
//

#import "YBPlayVC.h"
#import "YBPlayCtrlView.h"
#import <TXLiteAVSDK_Professional/V2TXLivePlayer.h>
#import <mach/mach.h>
#import "UserBulletWindow.h"
#import "YBSocketPlay.h"
#import "YBLiveEndView.h"
#import "YBCenterVC.h"
#import "YBLiveReportVC.h"
#import "MsgSysVC.h"
#import "YBImRoomSmallView.h"
#import <ZFPlayer/ZFPlayer.h>
#import <ZFPlayer/ZFPlayerControlView.h>
#import <ZFPlayer/ZFIJKPlayerManager.h>
#import "ZFCustomControlView.h"

@interface YBPlayVC ()<UserBulletWindowDelegate,UIScrollViewDelegate,V2TXLivePlayerObserver,V2TIMConversationListener> {
    
    NSString *_userType;                        //用户类型:普通用户-30;房间管理-40;主播-50;超管-60;
    int _userlistRefreshTime;                   //用户列表刷新时间
    NSTimer *_listTimer;                        //用户列表计时器
    UserBulletWindow *buttleView;               //用户信息卡
    int _firstStar;
    MsgSysVC *sysView;
    int unRead;
    CGFloat _changeScorllOffSetY;
    
    YBImRoomSmallView *_imListView;

}
@property(nonatomic,strong)UIImageView *pkBgIV;
@property(nonatomic,strong)TXView *videoPlayView;               //播放器
@property(nonatomic,strong)YBPlayCtrlView *playCtrlView;        //控制层
@property(nonatomic,strong)YBLiveEndView *playEndView;          //直播结束页面
@property(nonatomic,strong)UIScrollView *changeRoomScroll;      //房间切换底部scroll
@property (nonatomic, strong)V2TXLivePlayer *txLivePlayer;
@property (nonatomic, strong) ZFPlayerController *videoPlayer;
//@property (nonatomic, strong) ZFCustomControlView *fullControlView;

@end

@implementation YBPlayVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
    [self requestJmsg];
    if (_txLivePlayer) {
        [_txLivePlayer setPlayoutVolume:100];
    }
    if (_playCtrlView) {
        [_playCtrlView showGoodsBtnAnimaition];
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
    if (_txLivePlayer) {
        [_txLivePlayer setPlayoutVolume:0];
    }
    if (_playCtrlView) {
        [_playCtrlView removeGoodsBtnAnimation];
        _playCtrlView.keyBoardIsShow = NO;
        [_playCtrlView.chatTool.chatTF resignFirstResponder];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.naviView.hidden = YES;
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    self.navigationController.interactivePopGestureRecognizer.delegate =nil;
    //私信
    [self.view addSubview:self.changeRoomScroll];
    if (@available(iOS 11.0,*)) {
        self.changeRoomScroll.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self initPlayer];
    [_changeRoomScroll addSubview:self.pkBgIV];
    [_changeRoomScroll addSubview:self.playCtrlView];
    [self addNotification];
    _playDic = _listArray[_currentIndex];
    [self changeRoomReset];
    
}
-(void)changeRoomReset {
    [self releaseAllOfChangeRoom:YES];
    _userType = @"30";
    _firstStar = 0;
    
    [_playCtrlView clearChatList];
    _playCtrlView.playDic = _playDic;
    
    _changeRoomScroll.contentOffset = CGPointMake(0, _window_height*_currentIndex);
    
    _pkBgIV.frame = CGRectMake(0, _window_height*_currentIndex, _window_width, _window_height);
    _playCtrlView.frame = CGRectMake(0, _window_height*_currentIndex, _window_width, _window_height);
    _videoPlayView.frame = CGRectMake(0, _window_height*_currentIndex, _window_width, _window_height);
    [self changeLinkPlayer:NO toHostid:@""];
    
    [self bringPlayerToFront:NO];
    
    if ([minstr([_playDic valueForKey:@"isvideo"]) isEqual:@"1"]) {
        [self playWithVideoPlayer];
    }else{
        [self.txLivePlayer setRenderFillMode:V2TXLiveFillModeFill];
        if ([minstr([_playDic valueForKey:@"anyway"]) isEqual:@"1"]) {
            [self.txLivePlayer setRenderFillMode:V2TXLiveFillModeFit];
        }
        if ([minstr([_playDic valueForKey:@"isvideo"]) isEqual:@"1"]) {
            [self.txLivePlayer setRenderFillMode:V2TXLiveFillModeFill];
        }
        [self.txLivePlayer setRenderView:_videoPlayView];

        NSString *playUrl = [_playDic valueForKey:@"pull"];
        V2TXLiveCode result = [self.txLivePlayer startLivePlay:playUrl];
        NSLog(@"wangminxin-----%ld",result);
        if( result != 0)
        {
            [MBProgressHUD showPop:YZMsg(@"播放失败")];
            [self dismissVC];
        }
        if( result == 0){
            NSLog(@"播放视频");
        }
    }
    //进房间、链接socket
    [self enterRoom];
    //进场标题
    [self showTitle];
}
#pragma mark -视频播放器
-(ZFPlayerController *)videoPlayer{
    if(!_videoPlayer){
        ZFIJKPlayerManager *playerManager = [[ZFIJKPlayerManager alloc] init];
        NSString *ijkRef = [NSString stringWithFormat:@"Referer:%@\r\n",h5url];
        [playerManager.options setFormatOptionValue:ijkRef forKey:@"headers"];

        _videoPlayer =[ZFPlayerController playerWithPlayerManager:playerManager containerView:_videoPlayView];
        _videoPlayer.shouldAutoPlay = YES;
        _videoPlayer.allowOrentitaionRotation = NO;
        _videoPlayer.WWANAutoPlay = YES;
        //不支持的方向
        _videoPlayer.disablePanMovingDirection = ZFPlayerDisablePanMovingDirectionVertical;
        //不支持的手势类型
        _videoPlayer.disableGestureTypes =  ZFPlayerDisableGestureTypesPinch;
        /// 1.0是消失100%时候
        _videoPlayer.playerDisapperaPercent = 1.0;
        //功能
        @weakify(self)
        _videoPlayer.playerPrepareToPlay = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSURL * _Nonnull assetURL) {
            NSLog(@"准备");
            @strongify(self)
            
        };
        _videoPlayer.playerReadyToPlay = ^(id<ZFPlayerMediaPlayback>  _Nonnull asset, NSURL * _Nonnull assetURL) {
            @strongify(self)
            _playCtrlView.avatarEffect.hidden = YES;
            [self bringPlayerToFront:YES];
//            self.fullControlView.playDoc = self.playDic;

        };
        _videoPlayer.playerDidToEnd = ^(id  _Nonnull asset) {
            NSLog(@"结束");
            @strongify(self)
            [self.videoPlayer.currentPlayerManager replay];
        };
        _videoPlayer.orientationDidChanged = ^(ZFPlayerController * _Nonnull player, BOOL isFullScreen) {
            @strongify(self)
//            if (isFullScreen) {
//                self.fullControlView.hidden = NO;
//                self.videoPlayer.controlView = self.fullControlView;
//            }else{
//                self.fullControlView.hidden = YES;
//            }

        };

    }
    return _videoPlayer;
}

-(void)playWithVideoPlayer{
    NSString *playUrl = [_playDic valueForKey:@"pull"];
    self.videoPlayer.assetURL = [NSURL URLWithString:playUrl];
}
//- (ZFCustomControlView *)fullControlView {
//    YBWeakSelf;
//    if (!_fullControlView) {
//        _fullControlView = [[ZFCustomControlView alloc] init];
//        _fullControlView.btnEvent = ^(NSString *str) {
//            if ([str isEqual:@"focus"]){
//                [weakSelf guanzhuZhuBolela];
//            }
//        };
//
//    }
//    return _fullControlView;
//}

//显示进场标题
- (void)showTitle{
    if (minstr([_playDic valueForKey:@"title"]).length > 0) {
        CGFloat titleWidth = [PublicObj sizeWithString:minstr([_playDic valueForKey:@"title"]) andFont:[UIFont systemFontOfSize:14]].width;
        UIImageView *titleBackImgView = [[UIImageView alloc]initWithFrame:CGRectMake(_window_width, 95+statusbarHeight, 35+titleWidth+20, 30)];
        titleBackImgView.image = [UIImage imageNamed:@"moviePlay_title"];
        titleBackImgView.alpha = 0.5;
        titleBackImgView.layer.cornerRadius = 15;
        titleBackImgView.layer.masksToBounds = YES;
        [self.view addSubview:titleBackImgView];
        UIImageView *laba = [[UIImageView alloc]initWithFrame:CGRectMake(10, 7.5, 15, 15)];
        laba.image = [UIImage imageNamed:@"moviePlay_laba"];
        [titleBackImgView addSubview:laba];
        UILabel *titL = [[UILabel alloc]initWithFrame:CGRectMake(laba.right+10, 0, titleWidth+20, 30)];
        titL.text = minstr([_playDic valueForKey:@"title"]);
        titL.textColor = [UIColor whiteColor];
        titL.font = [UIFont systemFontOfSize:14];
        [titleBackImgView addSubview:titL];
        [UIView animateWithDuration:3 animations:^{
            titleBackImgView.alpha = 1;
            titleBackImgView.x = 10;
        }];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:2 animations:^{
                titleBackImgView.alpha = 0;
                titleBackImgView.x = -_window_width;
            } completion:^(BOOL finished) {
                [titleBackImgView removeFromSuperview];
            }];
        });
    }
}
-(void)initPlayer {
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isPlaying"];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    
    _videoPlayView = [[TXView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
    _videoPlayView.backgroundColor = UIColor.clearColor;
    [_changeRoomScroll addSubview:_videoPlayView];
    
    [self.txLivePlayer setRenderView:_videoPlayView];
}
-(void)bringPlayerToFront:(BOOL)isFront {
    if (isFront) {
        [_changeRoomScroll bringSubviewToFront:_pkBgIV];
        [_changeRoomScroll bringSubviewToFront:_videoPlayView];
        [_changeRoomScroll bringSubviewToFront:_playCtrlView];
    }else{
        [_changeRoomScroll sendSubviewToBack:_videoPlayView];
        [_changeRoomScroll sendSubviewToBack:_pkBgIV];
    }
}
-(void)destroyPusher {
    if(_txLivePlayer) {
        [_txLivePlayer stopPlay];
        _txLivePlayer = nil;
    }
    if(self.videoPlayer){
        [self.videoPlayer stop];
    }

}

-(V2TXLivePlayer *)txLivePlayer{
    if(!_txLivePlayer){
        _txLivePlayer = [[V2TXLivePlayer alloc] init];
        [_txLivePlayer setObserver:self];
        [_txLivePlayer enableObserveAudioFrame:YES];
        [_txLivePlayer setRenderFillMode:V2TXLiveFillModeFill];
    }
    return _txLivePlayer;
}
#pragma mark---liveplayObserver

- (void)onError:(id<V2TXLivePlayer>)player code:(V2TXLiveCode)code message:(NSString *)msg extraInfo:(NSDictionary *)extraInfo;
{
    NSLog(@"liveplay-error");
}
- (void)onWarning:(id<V2TXLivePlayer>)player code:(V2TXLiveCode)code message:(NSString *)msg extraInfo:(NSDictionary *)extraInfo;
{
    NSLog(@"liveplay-onWarning");
}
/**
 * 已经成功连接到服务器
 *
 * @param player    回调该通知的播放器对象。
 * @param extraInfo 扩展信息。
 */

- (void)onVideoPlaying:(id<V2TXLivePlayer>)player firstPlay:(BOOL)firstPlay extraInfo:(NSDictionary *)extraInfo;
{
    NSLog(@"moviplay不连麦视频播放开始");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _playCtrlView.avatarEffect.hidden = YES;
        [self bringPlayerToFront:YES];
    });
}

- (void)onAudioPlaying:(id<V2TXLivePlayer>)player firstPlay:(BOOL)firstPlay extraInfo:(NSDictionary *)extraInfo;{
    NSLog(@"onAudioPlaying");
}

/**
 * 视频加载事件
 *
 * @param player    回调该通知的播放器对象。
 * @param extraInfo 扩展信息。
 */
- (void)onVideoLoading:(id<V2TXLivePlayer>)player extraInfo:(NSDictionary *)extraInfo;{
    NSLog(@"onVideoLoading");
}

/**

/*
* 直播播放器分辨率变化通知
*
* @param player    回调该通知的播放器对象。
* @param width     视频宽。
* @param height    视频高。
*/
- (void)onVideoResolutionChanged:(id<V2TXLivePlayer>)player width:(NSInteger)width height:(NSInteger)height;
{
    
}

//#pragma mark - TXLivePlayListener
//-(void) onPlayEvent:(int)EvtID withParam:(NSDictionary*)param {
//    dispatch_async(dispatch_get_main_queue(), ^{
//        if (EvtID == PLAY_EVT_CONNECT_SUCC) {
//            NSLog(@"moviplay不连麦已经连接服务器");
//        }else if (EvtID == PLAY_EVT_RTMP_STREAM_BEGIN){
//            NSLog(@"moviplay不连麦已经连接服务器，开始拉流");
//        }else if (EvtID == PLAY_EVT_PLAY_BEGIN){
//            NSLog(@"moviplay不连麦视频播放开始");
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                _playCtrlView.avatarEffect.hidden = YES;
//                [self bringPlayerToFront:YES];
//            });
//        }else if (EvtID== PLAY_WARNING_VIDEO_PLAY_LAG){
//            NSLog(@"moviplay不连麦当前视频播放出现卡顿（用户直观感受）");
//        } else if (EvtID == PLAY_EVT_PLAY_END){
//            NSLog(@"moviplay不连麦视频播放结束");
//            [_txLivePlayer resume];
//        }else if (EvtID == PLAY_ERR_NET_DISCONNECT) {
//            NSLog(@"moviplay不连麦网络断连,且经多次重连抢救无效,可以放弃治疗,更多重试请自行重启播放");
//        }else if (EvtID == PLAY_EVT_CHANGE_RESOLUTION) {
//            NSLog(@"主播连麦分辨率改变");
//        }
//    });
//}
//-(void)onNetStatus:(NSDictionary *)param{
//
//}
#pragma mark - 进房间
-(void)enterRoom {
    YBWeakSelf;
    [[YBSocketPlay playSocketManeger]enterRoomAndConnectSocket:_playDic complete:^(NSString *socEvent, NSDictionary *socketDic) {
        if ([socEvent isEqual:@"0"]) {
            [weakSelf enterSuc:socketDic];
        }else {
            [MBProgressHUD showPop:socEvent];
            [weakSelf dismissVC];
        }
    }];
}
-(void)enterSuc:(NSDictionary *)roomDic {
    [self startSocketBlockMonitor];
    
    _userType = minstr([roomDic valueForKey:@"usertype"]);
    
    [_playCtrlView enterroomUpdateInfo:roomDic];
    
    _userlistRefreshTime = [minstr([roomDic valueForKey:@"userlist_time"]) intValue];
    if (_userlistRefreshTime < 10) {
        _userlistRefreshTime = 10;
    }
    if (!_listTimer) {
        _listTimer = [NSTimer scheduledTimerWithTimeInterval:_userlistRefreshTime target:self selector:@selector(reloadUserList) userInfo:nil repeats:YES];
    }
    
    NSDictionary *pkInfo = @{};
    if ([[roomDic valueForKey:@"pkinfo"] isKindOfClass:[NSDictionary class]]) {
        pkInfo = [roomDic valueForKey:@"pkinfo"];
        if (![minstr([pkInfo valueForKey:@"pkuid"]) isEqual:@"0"]) {
            [self changeLinkPlayer:YES toHostid:minstr([pkInfo valueForKey:@"pkuid"])];
            if ([minstr([pkInfo valueForKey:@"ifpk"]) isEqual:@"1"]) {
                [_playCtrlView socketLinkPKStart:pkInfo];
                NSMutableDictionary *pkDic = [NSMutableDictionary dictionary];
                [pkDic setObject:minstr([_playDic valueForKey:@"uid"]) forKey:@"pkuid1"];
                [pkDic setObject:minstr([pkInfo valueForKey:@"pk_gift_liveuid"]) forKey:@"pktotal1"];
                [pkDic setObject:minstr([pkInfo valueForKey:@"pk_gift_pkuid"]) forKey:@"pktotal2"];
                [_playCtrlView socketLinkPKProgress:pkDic];
            }
        }
    }

}
-(void)reloadUserList {
    [_playCtrlView timerReloadList];
}
#pragma mark - socket 监听
-(void)startSocketBlockMonitor {
    YBWeakSelf;
    //被超管关播
    [YBSocketPlay playSocketManeger].roomCloseByAdmin = ^(NSString *socEvent, NSDictionary *socketDic) {
        //进入结束页面
        [weakSelf requestLiveOverInfo];
    };
    //用户点亮
    [YBSocketPlay playSocketManeger].userLight = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketLightAnimation];
    };
    //发言
    [YBSocketPlay playSocketManeger].userSendMsg = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketChatDic:socketDic];
    };
    //用户离开
    [YBSocketPlay playSocketManeger].userLeave = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketUserLeave:socketDic];
    };
    //用户进入
    [YBSocketPlay playSocketManeger].userEnter = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketUserEnter:socketDic];
    };
    //直播关闭
    [YBSocketPlay playSocketManeger].liveOff = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf requestLiveOverInfo];
    };
    //系统消息
    [YBSocketPlay playSocketManeger].systemMsg = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketChatDic:socketDic];
    };
    //设置-取消管理
    [YBSocketPlay playSocketManeger].setAdmin = ^(NSString *socEvent, NSDictionary *socketDic) {
        _userType = minstr([socketDic valueForKey:@"usertype"]);
        [weakSelf.playCtrlView socketChatDic:socketDic];
    };
    //踢人
    [YBSocketPlay playSocketManeger].kickUser = ^(NSString *socEvent, NSDictionary *socketDic) {
        //退出房间
        [weakSelf dismissVC];
    };
    //送礼物
    [YBSocketPlay playSocketManeger].sendGift = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketSendGift:socketDic];
    };
    //在售商品
    [YBSocketPlay playSocketManeger].onSaleMsg = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketOnSale:socketDic];
    };
    //购买守护
    [YBSocketPlay playSocketManeger].buyGuardMsg = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketUpdateGuardMsg:socketDic];
    };
    //主播同意
    [YBSocketPlay playSocketManeger].linkHostAgree = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketHostIsAgree:YES andSocDic:socketDic];
    };
    //主播拒绝
    [YBSocketPlay playSocketManeger].linkHostUnAgree = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketHostIsAgree:NO andSocDic:socketDic];
    };
    //主播下麦用户
    [YBSocketPlay playSocketManeger].linkHostDisconnect = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketHostDisconnect:socketDic];
        NSString *touid = minstr([socketDic valueForKey:@"touid"]);
        if ([touid isEqual:[Config getOwnID]]) {
            NSString *playUrl = [_playDic valueForKey:@"pull"];
            V2TXLiveCode result = [weakSelf.txLivePlayer startLivePlay:playUrl];
            NSLog(@"wangminxin-----%ld",result);
        }

    };
    //主播忙碌
    [YBSocketPlay playSocketManeger].linkHostBusy = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketHostBusy:socketDic];
    };
    //主播超时
    [YBSocketPlay playSocketManeger].linkHostTimeout = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketHostTimeout:socketDic];
    };
    //主播主播开始
    [YBSocketPlay playSocketManeger].linkHostToHostStart = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf changeLinkPlayer:YES toHostid:minstr([socketDic valueForKey:@"pkuid"])];
    };
    //主播主播结束
    [YBSocketPlay playSocketManeger].linkHostToHostDisconnect = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf changeLinkPlayer:NO toHostid:@""];
        [weakSelf.playCtrlView destroyPkView];
    };
    //PK开始
    [YBSocketPlay playSocketManeger].linkPKSuc = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketLinkPKStart:socketDic];
    };
    //PK结果
    [YBSocketPlay playSocketManeger].linkPKResult = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketLinkPKReult:socketDic];
    };
    //PK进度
    [YBSocketPlay playSocketManeger].linkPKProgress = ^(NSString *socEvent, NSDictionary *socketDic) {
        [weakSelf.playCtrlView socketLinkPKProgress:socketDic];
    };
    
}

-(void)changeLinkPlayer:(BOOL)isLink toHostid:(NSString *)toHostid{
    _pkBgIV.hidden = !isLink;
    if (isLink) {
        [_playCtrlView showToHostInfoWithId:toHostid];
        _videoPlayView.frame = CGRectMake(0, _window_height*_currentIndex + 130+statusbarHeight, _window_width, _window_width*2/3);
    }else {
        [_playCtrlView destroyPkTohostInfo];
        _videoPlayView.frame = CGRectMake(0, _window_height*_currentIndex, _window_width, _window_height);
    }
//    [_txLivePlayer setupVideoWidget:_videoPlayView.bounds containView:_videoPlayView insertIndex:0];
    [_txLivePlayer setRenderView:_videoPlayView];
}

#pragma mark - 控制层回调
-(void)controlViewCallBack:(NSString *)eventType andEvnent:(NSDictionary *)eventDic {
    YBWeakSelf;
    if ([eventType isEqual:@"控制-关闭"]) {
        [weakSelf dismissVC];
    }
    
    if ([eventType isEqual:@"控制-直播聊天"]) {
        //发送socket  'ct'  [eventDic valueForKey:@"ct"]
        [[YBSocketPlay playSocketManeger] playSendMsg:minstr([eventDic valueForKey:@"ct"]) otherDic:@{@"usertype":_userType,@"guard_type":minstr([_playCtrlView.guardInfo valueForKey:@"type"])}];
    }
    
    if ([eventType isEqual:@"控制-信息卡"]) {
        [weakSelf showButtleView:minstr([eventDic valueForKey:@"id"])];
    }
    if ([eventType isEqual:@"控制-点亮"] && _firstStar == 0 && ![_userType isEqual:@"60"]) {
        _firstStar = 1;
        [[YBSocketPlay playSocketManeger] playSendLight:_userType otherDic:@{@"guard_type":minstr([_playCtrlView.guardInfo valueForKey:@"type"])}];
    }
    if ([eventType isEqual:@"控制-礼物"]) {
        [[YBSocketPlay playSocketManeger] playSendGift:eventDic];
    }
    if ([eventType isEqual:@"控制-关注"]) {
        [[YBSocketPlay playSocketManeger] playSendAttention];
    }
    if ([eventType isEqual:@"控制-私信"]) {
        [weakSelf liveRoomPraviteMsg];
    }
    if ([eventType isEqual:@"控制-购买守护"]) {
        //发送守护购买成功socket
        [[YBSocketPlay playSocketManeger] playSendBuyGuardSuc:eventDic];
    }
    if ([eventType isEqual:@"控制-用户申请连麦"]) {
        [[YBSocketPlay playSocketManeger] playSendUserHostLink];
    }
    if ([eventType isEqual:@"控制-用户连麦重新拉流"]) {
        [_txLivePlayer stopPlay];
        NSString *playurl = minstr([eventDic valueForKey:@"playurl"]);
        NSString *streamUrlWithSignature = minstr([eventDic valueForKey:@"streamUrlWithSignature"]);
        V2TXLiveCode liveCode = [_txLivePlayer startLivePlay:streamUrlWithSignature];
        NSLog(@"gethostlowurl---:%ld",liveCode);

        [[YBSocketPlay playSocketManeger] playSendUserLinkUrl:playurl];
    }
    if ([eventType isEqual:@"控制-用户断开连麦"]) {
        [[YBSocketPlay playSocketManeger] playSendUserDisconnect];
        NSString *playUrl = [_playDic valueForKey:@"pull"];
        V2TXLiveCode result = [weakSelf.txLivePlayer startLivePlay:playUrl];
        NSLog(@"wangminxin-----%ld",result);

    }
    
}
#pragma mark - 直播间私信列表开始
-(void)liveRoomPraviteMsg {
    [self destroyImListView];
    YBWeakSelf;
    _imListView = [YBImRoomSmallView showImListWithLiveUid:minstr([_playDic valueForKey:@"uid"])];
    _imListView.imSmallType = ImSmall_List;
    _imListView.imCtrEvent = ^(ImCtrType type, NSDictionary *ctrDic) {
        if (type == ImCtr_Dismiss) {
            [weakSelf destroyImListView];
        }
    };
}
-(void)destroyImListView {
    if (_imListView) {
        [_imListView removeFromSuperview];
        _imListView = nil;
    }
}
#pragma mark - 用户卡片信息开始
- (void)showButtleView:(NSString *)touid{
    if (buttleView) {
        [self removeButtleView];
    }
    buttleView = [[UserBulletWindow alloc]initWithUserID:touid andIsAnchor:NO andAnchorID:minstr([_playDic valueForKey:@"uid"])];
    buttleView.delegate  = self;
    [self.view addSubview:buttleView];
}
- (void)removeButtleView {
    [buttleView destroySubs];
    [buttleView removeFromSuperview];
    buttleView = nil;
}
-(void)socketShutUp:(NSString *)name andID:(NSString *)ID andType:(NSString *)type {
    [[YBSocketPlay playSocketManeger] playSendShutUpUser:@{@"type":type,@"touid":ID,@"touname":name}];
}
-(void)socketkickuser:(NSString *)name andID:(NSString *)ID {
    [[YBSocketPlay playSocketManeger] playSendKickUser:@{@"touname":name,@"touid":ID}];
}
-(void)pushZhuYe:(NSString *)IDS {
    YBCenterVC *center = [[YBCenterVC alloc]init];
    center.otherUid = IDS;
    center.isPush = YES;
    YBWeakSelf;
    center.followEvent = ^(NSString *isAttent) {
        [weakSelf updateFollowBtnIsAtten:[isAttent intValue]];
    };
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isPlaying"];
    [[YBBaseAppDelegate sharedAppDelegate] pushViewController:center animated:YES];
}

-(void)siXin:(NSString *)icon andName:(NSString *)name andID:(NSString *)ID andIsatt:(NSString *)isatt {
    [self destroyImListView];
    YBWeakSelf;
    [[YBMessageManager shareManager] getChatCellDataWithTouid:ID finish:^(int code, TConversationCellData * _Nonnull cellData) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (code == 0) {
                _imListView = [YBImRoomSmallView showImListWithLiveUid:[Config getOwnID]];
                _imListView.imSmallType = ImSmall_C2C;
                [_imListView goChatWithC2CWithConv:cellData];
                _imListView.imCtrEvent = ^(ImCtrType type, NSDictionary *ctrDic) {
                    if (type == ImCtr_Dismiss) {
                        [weakSelf destroyImListView];
                    }
                };
            }
        });
    }];
}
-(void)superAdmin:(NSString *)state andBanMsg:(NSString *)banMsg;{
    [[YBSocketPlay playSocketManeger] playSendStopLive:banMsg];
}

-(void)doReportAnchor:(NSString *)touid {
    YBLiveReportVC *vc = [[YBLiveReportVC alloc]init];
    vc.dongtaiId = touid;
    vc.isLive = YES;
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isPlaying"];
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:vc animated:YES];
}
#pragma mark - 用户卡片信息结束
#pragma mark - 退出房间
-(void)releaseAllOfChangeRoom:(BOOL)isChangeRoom {
    if (!isChangeRoom) {
        [self destroyPusher];
        [[NSNotificationCenter defaultCenter]removeObserver:self];
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isPlaying"];
        [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    }else{
        [_txLivePlayer stopPlay];
        if(self.videoPlayer){
            [self.videoPlayer stop];
        }

    }
    
    [_playCtrlView destroyCtrSubView];
    
    //计时器
    if (_listTimer) {
        [_listTimer invalidate];
        _listTimer = nil;
    }
    //socket
    [[YBSocketPlay playSocketManeger]playDisconnectSocket];

    //用户信息卡
    if (buttleView) {
        [buttleView removeFromSuperview];
        buttleView = nil;
    }
    [self destroyImListView];
}

//直接退出房间
-(void)dismissVC {
    [self releaseAllOfChangeRoom:NO];
    [self clickNaviLeftBtn];
}

#pragma mark - 直播结束
//进入结束页面
-(void)requestLiveOverInfo {
    //释放
    [self releaseAllOfChangeRoom:NO];
    
    [MBProgressHUD showMessage:@""];
    YBWeakSelf;
    [WYNetworking postWithUrl:@"Live.stopInfo" Dic:@{@"stream":minstr([_playDic valueForKey:@"stream"])} Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code == 0) {
            _playCtrlView.hidden = YES;
            NSDictionary *subdic = [info firstObject];
            [weakSelf createEndView:subdic];
        }else {
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
    
}
-(void)createEndView:(NSDictionary *)endDic {
    [self.view addSubview:self.playEndView];
    NSMutableDictionary *allDic = @{@"hostAvatar":minstr([_playDic valueForKey:@"avatar"]),@"hostName":minstr([_playDic valueForKey:@"user_nickname"])}.mutableCopy;
    [allDic addEntriesFromDictionary:endDic];
    [_playEndView updateData:allDic];
}
#pragma mark - 通知
-(void)addNotification {
    NSNotificationCenter *noti = [NSNotificationCenter defaultCenter];
    [noti addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [noti addObserver:self selector:@selector(keyboardWillHidden) name:UIKeyboardWillHideNotification object:nil];
//    [noti addObserver:self selector:@selector(forsixin:) name:@"sixinok" object:nil];
    [noti addObserver:self selector:@selector(reloadLiveplayAttion:) name:@"reloadLiveplayAttion" object:nil];
    [noti addObserver:self selector:@selector(youngModelTimeEnd:) name:ybYoungModelTimeEndEvent object:nil];
//    [noti addObserver:self selector:@selector(onRefreshConversations:) name:TUIKitNotification_TIMRefreshListener object:nil];
    [noti addObserver:self selector:@selector(updataFollow:) name:ybImC2CFollow object:nil];
    //获取所有未读消息
    [[V2TIMManager sharedInstance] addConversationListener:self];

}
-(void)updataFollow:(NSNotification *)not {
    NSString *isAttent = [NSString stringWithFormat:@"%@",not.object];
    [self updateFollowBtnIsAtten:[isAttent intValue]];
}
// 收到所有会话的未读总数变更通知
- (void)onTotalUnreadMessageCountChanged:(UInt64)totalUnreadCount {
    [self requestJmsg];
}

-(void)youngModelTimeEnd:(NSNotification *)not {
    [self dismissVC];
    [PublicObj layoutWindowPopLayer];
}
-(void)keyboardWillShow:(NSNotification *)not {
    //获取键盘的高度
    NSDictionary *userInfo = [not userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat height = keyboardRect.size.height;
    [UIView animateWithDuration:0.3 animations:^{
        if (_playCtrlView) {
            _playCtrlView.keyBoardIsShow = YES;
            _playCtrlView.top = - height+_window_height*_currentIndex;
            [_playCtrlView keyBoardNoticeIsShow:YES andHeight:height];
        }
    }completion:^(BOOL finished) {
        //很奇怪刘海屏offsety会变为37,这里重置一下
        [_playCtrlView.horScrollView setContentOffset:CGPointMake(_window_width, 0) animated:YES];
    }];
}
-(void)keyboardWillHidden {
    [UIView animateWithDuration:0.3 animations:^{
        if (_playCtrlView) {
            _playCtrlView.keyBoardIsShow = NO;
            _playCtrlView.top = 0+_window_height*_currentIndex;
            _playCtrlView.chatTool.hidden = YES;
            _playCtrlView.botBtnFunView.hidden = NO;
            [_playCtrlView keyBoardNoticeIsShow:NO andHeight:0];
        }
    }];
}
- (void)reloadLiveplayAttion:(NSNotification *)not{
    NSDictionary *dic = [not object];
    int isAttent = [minstr([dic valueForKey:@"isattent"]) intValue];
    [self updateFollowBtnIsAtten:isAttent];
}
-(void)updateFollowBtnIsAtten:(int)isAttent {
    [_playCtrlView updateFollowShow:(isAttent == 1 ? NO : YES)];
    if (isAttent == 1) {
        [[YBSocketPlay playSocketManeger] playSendAttention];
    }
}
#pragma mark - 私信监听
-(void)requestJmsg {
    
    [[YBImManager shareInstance]getAllUnredNumExceptUser:@[@"dsp_admin_1",@"dsp_fans",@"dsp_like",@"dsp_at",@"dsp_comment",@"dsp_user_live",@"goodsorder_admin"] complete:^(int allUnread) {
        unRead = allUnread;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (_playCtrlView) {
                [_playCtrlView updateUnread:unRead];
            }
        });
    }];
}
#pragma mark - set/get
- (UIImageView *)pkBgIV {
    if (!_pkBgIV) {
        _pkBgIV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
        _pkBgIV.contentMode = UIViewContentModeScaleAspectFill;
        _pkBgIV.clipsToBounds = YES;
        //_pkBgIV.image = [UIImage imageNamed:@"pk背景"];
        _pkBgIV.userInteractionEnabled = YES;
        _pkBgIV.hidden = YES;
        _pkBgIV.backgroundColor = RGB_COLOR(@"#1e1e1e", 1);
    }
    return _pkBgIV;
}
- (YBPlayCtrlView *)playCtrlView {
    if (!_playCtrlView) {
        YBWeakSelf;
        _playCtrlView = [[YBPlayCtrlView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
        _playEndView.backgroundColor = RGB_COLOR(@"#1e1e1e", 1);
        _playCtrlView.playDic = _playDic;
        _playCtrlView.playCtrEvent = ^(NSString *eventStr, NSDictionary *eventDic) {
            [weakSelf controlViewCallBack:eventStr andEvnent:eventDic];
        };
    }
    return _playCtrlView;
}
- (YBLiveEndView *)playEndView {
    if (!_playEndView) {
        YBWeakSelf;
        _playEndView = [[YBLiveEndView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
        _playEndView.liveEndEvent = ^{
            [weakSelf clickNaviLeftBtn];
        };
    }
    return _playEndView;
}

#pragma mark - 切换房间 s
- (UIScrollView *)changeRoomScroll {
    if (!_changeRoomScroll) {
        _changeRoomScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
        _changeRoomScroll.delegate = self;
        _changeRoomScroll.pagingEnabled = YES;
        _changeRoomScroll.showsVerticalScrollIndicator = NO;
        _changeRoomScroll.bounces = NO;
        
        _changeRoomScroll.contentSize = CGSizeMake(_window_width, _window_height*_listArray.count);
        _changeRoomScroll.contentOffset = CGPointMake(0, _window_height*_currentIndex);

        for (int i=0; i<_listArray.count; i++) {
            NSDictionary *listDic = _listArray[i];
            UIImageView *avaEffect = [PublicObj getAvatarEffectWithUrl:minstr([listDic valueForKey:@"avatar"])];
            avaEffect.frame = CGRectMake(0, _window_height*i, _window_width, _window_height);
            [_changeRoomScroll addSubview:avaEffect];
        }
    }
    return _changeRoomScroll;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == _changeRoomScroll) {
        _playCtrlView.keyBoardIsShow = NO;
        [_playCtrlView.chatTool.chatTF resignFirstResponder];
        _changeScorllOffSetY = _changeRoomScroll.contentOffset.y;
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == _changeRoomScroll) {
        _changeScorllOffSetY = _changeRoomScroll.contentOffset.y;
        if (_changeScorllOffSetY < 0 || (_currentIndex == _changeScorllOffSetY/_window_height)) {
            return;
        }
        NSInteger newIndex = _changeScorllOffSetY/_window_height;
        NSDictionary *newPlayDic = _listArray[newIndex];
        //[MBProgressHUD showMessage:@""];
        YBWeakSelf;
        [WYNetworking postWithUrl:@"Live.checkLive" Dic:@{@"liveuid":minstr([newPlayDic valueForKey:@"uid"]),@"stream":minstr([newPlayDic valueForKey:@"stream"])} Suc:^(int code, id info, NSString *msg) {
            [MBProgressHUD hideHUD];
            if (code == 0) {
                _currentIndex = newIndex;
                _playDic = newPlayDic;
                [_txLivePlayer stopPlay];
                if(self.videoPlayer){
                    [self.videoPlayer stop];
                }

                [weakSelf changeRoomReset];
            }else {
                [MBProgressHUD showPop:msg];
            }
        } Fail:^(id fail) {
            [MBProgressHUD hideHUD];
        }];
    }
}
#pragma mark - 切换房间 e
@end
